package judesart.app.server;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import judesart.app.service.ImageService;
import judesart.common.bean.ApplicationContextProvider;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

public class ImagesDownloadServlet extends HttpServlet implements Servlet {
    private final static Log LOGGER = LogFactory.getLog(ImagesDownloadServlet.class);

    ImageService imageService = ApplicationContextProvider.getCtx().getBean(
            ImageService.class);
    MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService("jaw-images");

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        LOGGER.debug(" > ImagesDownloadServlet.doGet [" + req.getQueryString()
                + "]");

        Image image;
        if (memcacheService.contains(req.getQueryString())) {
            image = (Image) memcacheService.get(req.getQueryString());

        } else {
            String imageId = req.getParameter("id");
            String size = req.getParameter("size");
            Integer width = null;
            Integer height = null;
            if (size != null) {
                String[] split = size.trim().split("x");
                if (split.length > 1) {
                    width = Integer.parseInt(split[0]);
                    height = Integer.parseInt(split[1]);
                }
            }
            String crop = req.getParameter("crop");
            try {
                image = imageService.getImageConstrained(new Long(imageId),
                        width, height, "true".equalsIgnoreCase(crop));
                try {
                    memcacheService.put(req.getQueryString(), image);
                } catch (Throwable e) {
                    LOGGER.error("Unable to put image in cache", e);
                }
            } catch (NumberFormatException e) {
                LOGGER.debug("invalid image id [" + imageId + "]");
                image = null;
            }
        }
        if (image != null) {
            resp.setContentType("image/" + image.getFormat().name());
            LOGGER.debug(" > resp.setContentType " + "image/"
                    + image.getFormat().name());
            LOGGER.debug(" > image.getData() " + image.getImageData().length);
            resp.getOutputStream().write(image.getImageData());
        }
    }
}
